package com.tanhua.manage.job;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserReceviveSoundApi;
import com.tanhua.manage.service.SummaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class AnalysisJob {

    @Autowired
    private SummaryService summaryService;

    @Scheduled(cron = "* 0/30 * * * ?") //定时执行方法
    public void analysis(){
        log.info("=============执行统计开始==============");
        summaryService.analysis();
        log.info("=============执行统计结束==============");
    }


    @Reference
    private UserReceviveSoundApi userReceviveSoundApi;

    @Reference
    private SoundApi soundApi;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer webServer;

    //定时任务，还原剩余次数
    @Scheduled(cron = "0/10 * * * * ?")
    public void clearRemaining(){
        log.info("=============还原桃花传音剩余次数==============");
        userReceviveSoundApi.clearRemaining();
        log.info("=============还原桃花传音剩余次数完成，余数2==============");
    }

    //定时任务，清理已经被接收的音频数据
    @Scheduled(cron = "0/10 * * * * ?")
    public void clearSound(){
        log.info("=============清理已被接收的音频==============");
        List<Sound> list = soundApi.findByState();
        if(list != null){
            for (Sound sound : list) {
                try {
                    String soundUrl = sound.getSoundUrl();
                    StorePath storePath = StorePath.parseFromUrl(soundUrl);
                    storageClient.deleteFile(storePath.getGroup(),storePath.getPath());
                    log.info("=============正在删除已读的音频文件==============");
                } catch (Exception e) {
                    log.warn(e.getMessage());
                }
            }
        }
        soundApi.clearSound();
        log.info("=============清理已被接收的音频完成==============");
    }


}
